package com.raidan.dclog.core.parser.text;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.regex.Matcher;

import com.raidan.dclog.core.parser.ParseLineException;

/**
 * Main class for parsing userip.log
 * 
 * @author raidan
 * @deprecated
 */
public class UsersTextParser extends AbstractTextParser {

	@Override
	protected void processLine(int linePos, String line, PreparedStatement statement) throws SQLException,
			ParseLineException {

		Matcher matcher = super.getLinePattern().matcher(line);

		if (!matcher.find(0)) {
			throw new ParseLineException("Unable to propery parse line '" + line + "' by pattern '"
					+ super.getLinePattern().toString() + "'.");
		}

		String ip = matcher.group(1);
		String username = matcher.group(2);
		String hub = matcher.group(3);
		String datetime = matcher.group(4);

		// Избавляемся от возможного лишнего символа в начале файла UTF
		if (linePos == 1) {
			char ch = ip.charAt(0);
			if (ch < '0' || ch > '9') {
				ip = ip.substring(1);
			}
		}

		statement.setString(1, ip); // ip
		statement.setString(2, username); // username
		statement.setString(3, hub); // hub

		try {
			statement.setTimestamp(4, new java.sql.Timestamp(super.getDateTimeFormatter().parse(datetime).getTime())); // date
		} catch (ParseException pe) {
			throw new ParseLineException("Unable to properly parse date for template '"
					+ super.getDateTimeFormatter().toPattern() + "' in line '" + line + "': " + pe.getMessage());
		}

		statement.addBatch();
	}

	@Override
	protected String getSQLInsert() {
		return "insert into users (ip, username, hub, changed) values (?,?,?,?)";
	}

	@Override
	public String getName() {
		return "Users logs (username, ip, hub)";
	}

	@Override
	protected String getFileName() {
		return "userip.log";
	}

	@Override
	protected String getPattern() {
		return "([^;]*);(.*);([^;]*);(.*)";
	}
}
